import { produce } from "immer";
import { StoreConfig, Store, Query } from "@datorama/akita";
import { Message, MessageItem } from "@/models/Message";

function createInitialState(): Message {
  return {
    enterMsg: "",
    notifyMsg: {},
    isSDKReady: false, //TIMSDK是否已初始化完成
    groupId: "",
    msgList: [],  //已接收到的消息
    tuwenMsgList: [], //等待的先审后发消息
  }
}

@StoreConfig({ name: "messages", producerFn: produce, resettable: true })
export class MessageStore extends Store<Message> {
  private static _instance: MessageStore;

  constructor() {
    super(createInitialState())
  }

  //单例方法
  public static getInstance(): MessageStore {
    if (this._instance == null) {
      this._instance = new MessageStore();
    }
    return this._instance;
  }
}

export class MessageQuery extends Query<Message> {
  isSDKReady$ = this.select("isSDKReady");
  groupId$ = this.select("groupId");
  enterMsg$ = this.select("enterMsg");
  notifyMsg$ = this.select("notifyMsg");
  msgList$ = this.select("msgList");
  tuwenMsgList$ = this.select("tuwenMsgList");

  isLoading$ = this.selectLoading();

  get isSDKReady(): boolean {
    return this.getValue().isSDKReady;
  }
  get groupId(): string {
    return this.getValue().groupId;
  }
  get enterMsg(): string {
    return this.getValue().enterMsg;
  }
  get notifyMsg(): Record<string, any> {
    return this.getValue().notifyMsg;
  }
  get msgList(): MessageItem[] {
    return this.getValue().msgList;
  }
  get tuwenMsgList(): MessageItem[] {
    return this.getValue().tuwenMsgList;
  }

  constructor(protected store: MessageStore) {
    super(store);
  }
}

export const makeStore = (): [MessageStore, MessageQuery] => {
  const store = MessageStore.getInstance();
  const query = new MessageQuery(store);

  return [store, query];
};